<template>
  <div class="ProductList-container all-night-layout">
    <div style="display: flex; align-items: center">
      <el-input
        placeholder="请输入内容"
        prefix-icon="el-icon-search"
        v-model="keyword"
        style="width: 300px; margin-right: 10px"
        clearable
      >
      </el-input>
      <el-button
        type="primary"
        style="display: flex; margin: 1rem 0"
        @click="centerDialogVisible = true"
        icon="el-icon-plus"
        >添加商品</el-button
      >
    </div>
    <!-- 添加商品 -->
    <el-dialog
      title="添加商品"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <el-form
        :model="addProductForm"
        :rules="rules"
        ref="addProductForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商品描述" prop="desc">
          <el-input v-model="addProductForm.desc" id="desc"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="addProductForm.price" id="price"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="weight">
          <el-input v-model="addProductForm.weight" id="weight"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProduct">确 定</el-button>
      </span>
    </el-dialog>
    <el-table :data="filterData" border style="width: 100%; border-radius: 5px">
      <el-table-column label="编号" width="80" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="商品描述" width="550" prop="desc">
      </el-table-column>
      <el-table-column label="商品价格" width="100">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.price }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="商品重量" width="100">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.weight }}kg</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="200" prop="date">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
          >
            <i class="el-icon-edit">编辑</i>
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            <i class="el-icon-delete">删除</i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 30, 40]"
      :page-size="pageSize"
      :layout="layout"
      :total="total"
      style="display: flex; margin-top: 1rem"
    >
    </el-pagination>
    <!-- 编辑功能部分 -->
    <el-dialog
      title="商品详情修改"
      :visible.sync="DialogVisible2"
      width="30%"
      center
    >
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="商品描述">
          <el-input
            type="textarea"
            v-model="formInline.desc"
            class="modify-box-area"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input-number
            v-model="formInline.price"
            controls-position="right"
            :min="1"
            :max="10000"
            :precision="2"
            :step="10"
          ></el-input-number>
          &nbsp;
          <span>元</span>
        </el-form-item>
        <el-form-item label="商品重量">
          <el-input-number
            v-model="formInline.weight"
            controls-position="right"
            :min="1"
            :max="10"
            :precision="2"
          ></el-input-number>
          &nbsp;
          <span>kg</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { formatDate } from "@/utils/formatDate.js"; //引入获取当前时间函数
import { cloneDeep } from "lodash"; // 安装lodash库
import axios from "axios";
export default {
  name: "Product-list",
  data() {
    return {
      currentPage: 1, //当前页数
      pageSize: 5, //每页显示个数
      total: 0, //页码总数
      layout: "total, sizes, prev, pager, next, jumper", //组件布局
      selectedRowIndex: "", //修改信息时把当前修改行的下标存起来，用于保存备用
      centerDialogVisible: false,
      DialogVisible2: false,
      keyword: "",
      tableData: [], //总数据
      filterData: [], //过滤后的数据
      addProductForm: {
        desc: "",
        price: "",
        weight: "",
        date: "",
      },
      formInline: {
        //点击操作后的数据项
        desc: "",
        price: "",
        weight: "",
        date: "",
      },
      rules: {
        desc: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    keyword: {
      // 搜索功能
      handler() {
        if (this.keyword) {
          //item用于表示数组tableData中的每个元素
          this.filterData = this.tableData.filter((item) => {
            return item.desc.indexOf(this.keyword) !== -1;
          });
          this.total = this.filterData.length;
          this.layout = "total"; //搜索时仅显示页码总数
        } else {
          this.layout = "total, sizes, prev, pager, next, jumper"; //不搜索时展示所有分页组件
          this.updateDisplayData();
        }
      },
    },
  },
  mounted() {
    this.GetProduct();
  },
  methods: {
    // 搜索功能
    handleSearch() {
      if (this.keyword) {
        this.filterData = this.tableData.filter((item) => {
          return item.desc.indexOf(this.keyword) !== -1;
        });
        this.total = this.filterData.length;
        this.layout = "total"; //搜索时仅显示页码总数
      } else {
        this.layout = "total, sizes, prev, pager, next, jumper"; //不搜索时展示所有分页组件
        this.updateDisplayData();
      }
    },
    // 调用数据
    GetProduct() {
      axios
        .get("/product/list")
        .then(({ data: res }) => {
          console.log(res);
          if (res.status === 200) {
            this.tableData = res.ProductList;
            this.updateDisplayData();
          }
        })
        .catch(function (error) {
          // 处理错误情况
          console.log(error);
          this.$message.error("错了哦，这是一条错误消息");
        });
    },
    // 操作按钮
    handleEdit(index, row) {
      this.formInline = cloneDeep(row);
      this.selectedRowIndex = index;
      console.log(index, row);
      this.DialogVisible2 = true;
    },
    // 商品详情修改确定按钮
    confirm() {
      this.formInline.date = formatDate("YY-MM-DD hh:mm:ss");
      this.tableData.splice(this.selectedRowIndex, 1, this.formInline);
      console.log(this.selectedRowIndex, this.formInline);
      this.selectedRowIndex = "";
      this.DialogVisible2 = false;
    },
    // 删除按钮
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.tableData.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 添加商品
    addProduct() {
      this.addProductForm.date = formatDate("YY-MM-DD hh:mm:ss");
      this.tableData.push({ ...this.addProductForm });
      this.updateDisplayData();
      // 使用展开语法和解构赋值复制对象，避免对原始数据的更改
      this.centerDialogVisible = false;
      this.$nextTick(() => {
        this.$refs["addProductForm"].resetFields();
      });
      this.$message({
          message: '添加成功！',
          type: 'success'
        });
    },
    //分页部分操作-处理每页显示条数变化
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.updateDisplayData();
    },
    // 分页部分操作- 处理当前页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.updateDisplayData();
    },
    // 更新显示部分数据
    updateDisplayData() {
      const startIndex = (this.currentPage - 1) * this.pageSize; // 计算起始索引
      const endIndex = startIndex + this.pageSize; // 计算结束索引
      this.total = this.tableData.length; //计算页码总数
      this.filterData = this.tableData.slice(startIndex, endIndex); // 更新展示的数据
    },
  },
};
</script>
<style lang="scss" scoped>
// 商品详情修改-商品描述
.modify-box-area {
  width: 300px;
}
.ProductList-container{
  background-color: #fff;
      border-radius: 5px;
      margin-top: 1rem;
      padding: 0 1.5rem 1rem;
}
</style>
